package com.itheima.jdbc;

import com.itheima.pojo.Account;
import org.junit.jupiter.api.Test;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/*
    JDBC API 详解:Result
 */
public class JDBCDemo5_ResultSet {
    /*
        执行DQL语句
        @throws Exception
     */
   /* @Test
    public void testResultSet() throws SQLException {
        //1.注册驱动
//        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接 :如果连接的是本机mysql并且端口默认的3306 可以简化书写
        String url="jdbc:mysql:///db1?useSSL=false";
        String username="root";
        String password="1234";
        Connection conn = DriverManager.getConnection(url, username, password);

      //3.定义sql
        String sql = "select * from account";

        //4.获取statement对象
        Statement stmt = conn.createStatement();

        //5.执行sql
        ResultSet rs = stmt.executeQuery(sql);

        //6.处理结果，遍历rs中所有的数据
        //6.1光标向下移动一行，并且判断当前行事是否有数据
        while (rs.next()) {
            //6.2获取数据 getXXX()
            int id = rs.getInt("id");
            String name = rs.getString("name");
            double money = rs.getDouble("money");

            System.out.println(id);
            System.out.println(name);
            System.out.println(money);

            System.out.println("-----------");
        }
    }*/
    @Test
    public void testResultSet2() throws SQLException {
        //1.注册驱动
//        Class.forName("com.mysql.jdbc.Driver");
        //2.获取连接 :如果连接的是本机mysql并且端口默认的3306 可以简化书写
        String url="jdbc:mysql:///db1?useSSL=false";
        String username="root";
        String password="1234";
        Connection conn = DriverManager.getConnection(url, username, password);

        //3.定义sql
        String sql = "select * from account";

        //4.获取statement对象
        Statement stmt = conn.createStatement();

        //5.执行sql
        ResultSet rs = stmt.executeQuery(sql);

        //创建集合
        List<Account> list = new ArrayList<>();
        //6.处理结果，遍历rs中所有的数据
        //6.1光标向下移动一行，并且判断当前行事是否有数据
        while (rs.next()) {
            Account account = new Account();
            //6.2获取数据 getXXX()
            int id = rs.getInt("id");
            String name = rs.getString("name");
            double money = rs.getDouble("money");

            //赋值
            account.setId(id);
            account.setName(name);
            account.setMoney(money);

            //存入集合
            list.add(account);
        }
        System.out.println(list);
        rs.close();
        stmt.close();
        conn.close();
    }
}
